package middleware

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"user-srv/appconfig"
	"user-srv/common"
)

type AuthTokenMiddleware struct {
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		//获取token
		get := r.Header.Get("token")
		if get == "" {
			httpx.ErrorCtx(r.Context(), w, errors.New("token 不存在 "))
		}
		//解析token
		payload, err := common.ParseJwtTokenPayload(get, appconfig.AppConf1.JwtConfig.AccessSecret)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		fmt.Println(payload)
		value := context.WithValue(r.Context(), "userId", payload)
		next(w, r.WithContext(value))
	}
}
